<?php

namespace Xtsb\Cims\File;


use Mpdf\Mpdf;

/**
 * @WaterMarkPdf
 * @property Mpdf $pdf
 * @property $instance
 * @property $input_file
 * @property $exception
 */
class WaterMarkPdf
{

  static $instance;
  static $pdf;
  static $input_file;
  public $exception;

  //示例
  public function demo(){
    WaterMarkPdf::getInstance("test.pdf")->text('watermark')->save('test_text.pdf');
    WaterMarkPdf::getInstance("test.pdf")->image('watermark.png')->save('test_image.pdf');
  }

  // 可选：在这里可以添加初始化代码
  private function __construct() {
  }

  // 如果实例不存在，则创建一个新实例并返回
  public static function getInstance($input_file) {
    if (!self::$instance) {
      self::$instance = new self();
    }
    self::$input_file = $input_file;
    self::$pdf = new Mpdf(['mode' => 'zh-cn']);
    return self::$instance;
  }

  //文字水印 捕捉发票类pdf报错直接返回
  public function text($text){
    try{
      $this->exception = false;
      $pdf = self::$pdf;
      $pages = $pdf->setSourceFile(self::$input_file);
      for ($pageNumber = 1; $pageNumber <= $pages; $pageNumber++) {
        $tid = $pdf->importPage($pageNumber);
        $pdf->AddPage();
        $pdf->useTemplate($tid);
        $pdf->watermark($text);
        $pdf->showWatermarkText = true;
      }
    }catch (\setasign\Fpdi\PdfParser\PdfParserException $e){
      $this->exception = true;
      return $this;
    }
    return $this;
  }

  //图片水印 捕捉发票类pdf报错直接返回
  public function image($image_file){
    try{
      $this->exception = false;
      $pdf = self::$pdf;
      $pages = $pdf->setSourceFile(self::$input_file);
      for ($pageNumber = 1; $pageNumber <= $pages; $pageNumber++) {
        $tid = $pdf->importPage($pageNumber);
        $pdf->AddPage();
        $pdf->useTemplate($tid);
        $pdf->watermarkImg($image_file,.2);
        $pdf->showWatermarkImage = true;
      }
    }catch (\setasign\Fpdi\PdfParser\PdfParserException $e){
      $this->exception = true;
      return $this;
    }
    return $this;
  }


  //保存文件
  public function save($out_file){
    if($this->exception === false){
      self::$pdf->Output($out_file, 'F');
      return $out_file;
    }
    return false;
  }

}